<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button
            icon="plus"
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <!-- 1.定义需要根据字段排序的字段名称 -->
        <el-table border :data="list" :default-sort="{ prop: 'workNumber' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              类型：{{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <!-- 2.保证字段列上声明了prop属性和sortable属性 -->
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" fixed="right" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px; margin-top: 10px"
        >
          <el-pagination
            :total="total"
            :page-size="pageParams.size"
            layout="prev, pager, next"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 使用 -->
    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="hCloseDialog"
    >
      <!-- @close 关闭弹层 @update-empolyee -->
      <addor-edit
        ref="AddEmployee"
        @close="showDialog = false"
        @update-empolyee="hUpdateEmpolyee"
      />
    </el-dialog>

    <el-dialog
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
    >
      <!-- 方案1:v-if="showDialogRole" -->
      <!-- 方案2: 在父组件中点击分配角色时，直接调用子组件中方法获取数据给子组件添加引用-->
      <assign-role
        ref="assignRole"
        :employee-id="curEmployeId"
        @update-close="hUpdateClose"
        @close="showDialogRole=false"
      />
    </el-dialog>
  </div>
</template>
<script>
// import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import addorEdit from './empDialog'
import AssignRole from './assignRole'

const hireType = {}
EmployeeEnum.hireType.forEach((item) => {
  hireType[item.id] = item.value
})
console.log('枚举信息', EmployeeEnum.hireType, hireType)

export default {
  components: {
    'addor-edit': addorEdit,
    AssignRole // 注册组件
  },
  data() {
    return {
      curEmployeId: '', // 当前的员工编号
      showDialogRole: false,
      showDialog: false,
      list: [],
      total: 0,
      pageParams: {
        page: 1,
        size: 5
      }
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams)
        console.log('从后端获取的员工列表是', res)
        const { rows, total } = res.data
        this.list = rows
        this.total = total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    async doDel(id) {
      try {
        const rs = await delEmployee(id)
        console.log('删除之后的结果是', rs)
        // 1. 提示
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        // 2. 重新加载数据
        this.loadEmployeeList()
      } catch (err) {
        this.$message.error('删除失败')
      }
    },
    hAssignRole(id) {
      // console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curEmployeId = id
      // console.log('父组件', this.curEmployeId)
      // this.$nextTick
      // 直接找到子组件，调用方法去获取最新的数据
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
        // console.log('子组件中的props', this.$refs.assignRole.employeeId)
      })
    },
    // 用户点击了删除
    hDel(id) {
      this.$confirm('你确定要删除吗')
        .then(() => {
          this.doDel(id)
        })
        .catch(() => {})
    },
    formatEmployment(id) {
      // 对后端返回的类型的编码进行翻译 ，还原成 中文
      // const rs = EmployeeEnum.hireType.find(item => item.id === id)
      // return rs.value
      return hireType[id]
    },
    hCurrentChange(curPage) {
      this.pageParams.page = curPage
      this.loadEmployeeList()
    },
    hUpdateEmpolyee() {
      this.showDialog = false

      this.loadEmployeeList()
    },
    // 关闭弹层
    // 1. 在表单中点击取消（添加成功）
    // 2. 弹层上点击 X
    hCloseDialog() {
      // 相当于是在父组件中去执行子组件中方法
      // 去清空 子组件中的表单数据和校验结果
      // 子组件.resetForm()
      // console.log('在父组件中获取子组件的引用', this.$refs.AddEmployee)
      this.$refs.AddEmployee.resetForm()
    },
    // 用户分配角色成功
    hUpdateClose() {
      this.showDialogRole = false
      this.loadEmployeeList()
    },
    // 导出execl
    async hExportExcel() {
      // 1. 获取数据
      const res = await getEmployeeList(this.pageParams)
      console.log('有效数据:', res.data.rows)
      // 2. 处理数据
      const obj = this.transData(res.data.rows)
      // 3.导出
      import('@/vendor/export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: obj.header, // ['姓名','工资'], // 表头 必填
          data: obj.data, // [
          //   ['刘备', 800],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'employee-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    transData(rows) {
      // 写代码
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // 写代码
      // header => ['id', '手机号', '用户名', ... ]
      // data => [
      //   ["604f764971f93f3ac8f365c2", "13800000002", "管理员",.... ]
      // ]
      const enKeys = Object.keys(rows[0])
      const header = enKeys.map(enKey => {
        return map[enKey]
      })

      const data = rows.map(obj => {
        return Object.values(obj)
      })

      return { header, data }
    }
  }
}
</script>

